package com.baizhi.cmfz.controller;

import com.baizhi.cmfz.annotation.LogAnnotation;
import com.baizhi.cmfz.entiy.Banner;
import com.baizhi.cmfz.service.BannerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


//@RestController相当于@Controller 和@ResponseBody，声明当前类为控制器
// 类中所有的方法 响应数据都会序列化为json

@RestController
@RequestMapping("banner")
public class BannerController {

    @Autowired
    private BannerService service;

    private Logger logger= LoggerFactory.getLogger(BannerController.class);

    @RequestMapping("selectAllBanner")
    @LogAnnotation("查看轮播图")
    public Map  selectAllBanner(int page,int rows,String bannerName){
        Map map = service.selectAllBanner(page, rows, bannerName);
        //打印对象方式①:字符串拼接
        logger.debug(""+map.get("rows"));
        //打印对象方式②：{}占位符
        logger.debug("上师数据：{}",map.get("rows"));
        return map;
    }

    //添加
    @RequestMapping("add")
    @LogAnnotation("添加轮播图")
    public Map addBanner(Banner banner, MultipartFile image, HttpServletRequest request) throws IOException {
        HashMap map = new HashMap();
        logger.debug("banner"+banner);
        //String realPath = request.getRealPath("upload");//获取upload文件的路径
        String newName = new Date   ().getTime() + image.getOriginalFilename();
        System.out.println("newName"+newName);
        File file=new File("D:"+File.separator + "devData"+ File.separator + "项目测试数据存放"+ File.separator + "image" + File.separator  +newName);
        image.transferTo(file);//转为磁盘文件
        banner.setBannerImageUrl("/img/"+newName);
        try {
            service.add(banner);
            map.put("isAdd",true);
        } catch (Exception e) {
            map.put("isAdd",false);
            e.printStackTrace();
        }
        return map;
    }
    @RequestMapping("update")
    @LogAnnotation("更新轮播图")
    public Map updateBanner(Banner banner){
        HashMap map = new HashMap();
        logger.debug("banner"+banner);
        try {
            service.update(banner);
            map.put("isUpdate",true);
        } catch (Exception e) {
            map.put("isUpdate",false);
            e.printStackTrace();
        }
        return map;
    }
}
